<template>
  <div class="service-container">
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <h3>访客预约管理</h3>
          <div class="header-right">
            <el-button type="primary" @click="handleAdd" class="add-btn"><el-icon><Plus /></el-icon>添加预约</el-button>
            <div class="search-toggle-area">
              <el-button class="search-toggle-button" @click="toggleSearchBar">
                <el-icon><Search /></el-icon>
              </el-button>
              <el-form :inline="true" :model="searchForm" class="search-form" :class="{'is-hidden': !showSearchBar}">
                <el-form-item label="访客姓名">
                  <el-input v-model="searchForm.name" placeholder="请输入访客姓名" clearable />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 140px;">
                    <el-option label="待审批" :value="0" />
                    <el-option label="已批准" :value="1" />
                    <el-option label="已拒绝" :value="2" />
                    <el-option label="已入园" :value="3" />
                    <el-option label="已离园" :value="4" />
                    <el-option label="已取消" :value="5" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-bar" v-if="false">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="访客姓名">
            <el-input v-model="searchForm.name" placeholder="请输入访客姓名" clearable size="small" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable size="small" />
          </el-form-item>
          <el-form-item label="访问日期">
            <div class="date-filter-container">
              <el-date-picker
                v-model="searchForm.visitDate"
                type="date"
                placeholder="选择日期"
                style="width: 180px"
                value-format="YYYY-MM-DD"
                :editable="false"
                size="small"
              />
              <el-select v-model="searchForm.dateCondition" style="width: 100px" :editable="false" size="small">
                <el-option label="之前" value="before" />
                <el-option label="之后" value="after" />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable size="small">
              <el-option label="待审批" :value="0" />
              <el-option label="已批准" :value="1" />
              <el-option label="已拒绝" :value="2" />
              <el-option label="已入园" :value="3" />
              <el-option label="已离园" :value="4" />
              <el-option label="已取消" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" size="small">查询</el-button>
            <el-button @click="resetSearch" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color:'#606266' }"
      >
        <el-table-column prop="visitor.name" label="访客姓名" width="100" align="center" header-align="center" />
        <el-table-column prop="visitor.phone" label="联系电话" width="150" align="center" header-align="center" />
        <el-table-column label="接待企业" min-width="200" align="center" header-align="center">
          <template #default="{ row }">
            <span v-if="row.visited_company">{{ row.visited_company.company_name }}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="visit_purpose" label="访问目的" min-width="180" align="center" header-align="center" />
        <el-table-column label="访问时间" width="180" align="center" header-align="center">
            <template #default="{ row }">
                {{ formatDateTime(row.expected_visit_time) }}
            </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center" header-align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center" header-align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status === 0" type="success" link @click="handleApprove(scope.row)">批准</el-button>
            <el-button v-if="scope.row.status === 0" type="danger" link @click="handleReject(scope.row)">拒绝</el-button>
            <el-button v-if="scope.row.status === 1" type="warning" link @click="handleCheckIn(scope.row)">入园</el-button>
            <el-button v-if="scope.row.status === 3" type="info" link @click="handleCheckOut(scope.row)">离园</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-empty v-if="tableData.length === 0 && !loading" description="暂无访客预约数据" class="empty-data-placeholder"></el-empty>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="appointmentFormRef" :model="appointmentForm" :rules="appointmentFormRules" label-width="100px">
        <el-form-item label="选择访客" prop="visitor_id">
          <el-select
            v-model="appointmentForm.visitor_id"
            filterable
            remote
            reserve-keyword
            placeholder="请输入访客姓名或手机号搜索"
            :remote-method="searchVisitorsMethod"
            :loading="searchLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in visitorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接待企业" prop="visited_company_id">
          <el-select v-model="appointmentForm.visited_company_id" placeholder="请选择接待企业" clearable filterable style="width: 100%">
            <el-option v-for="item in companyOptions" :key="item.company_id" :label="item.company_name" :value="item.company_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="访问目的" prop="visit_purpose">
          <el-input v-model="appointmentForm.visit_purpose" placeholder="请输入访问目的" />
        </el-form-item>
        <el-form-item label="访问日期" prop="visitDate">
            <el-date-picker v-model="appointmentForm.visitDate" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="访问时间" prop="visitTime">
            <el-time-picker v-model="appointmentForm.visitTime" placeholder="选择时间" style="width: 100%" format="HH:mm" value-format="HH:mm:ss" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="访客预约详情" v-model="viewDialogVisible" width="600px">
        <el-descriptions :column="1" border v-if="appointmentDetail.visitor">
            <el-descriptions-item label="访客姓名">{{ appointmentDetail.visitor.name }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ appointmentDetail.visitor.phone }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ appointmentDetail.visitor.id_card }}</el-descriptions-item>
            <el-descriptions-item label="接待企业">{{ appointmentDetail.visited_company?.company_name || '无' }}</el-descriptions-item>
            <el-descriptions-item label="访问目的">{{ appointmentDetail.visit_purpose }}</el-descriptions-item>
            <el-descriptions-item label="访问时间">{{ formatDateTime(appointmentDetail.expected_visit_time) }}</el-descriptions-item>
            <el-descriptions-item label="状态">
                <el-tag :type="getStatusType(appointmentDetail.status)">{{ getStatusText(appointmentDetail.status) }}</el-tag>
            </el-descriptions-item>
        </el-descriptions>
        <template #footer>
            <span class="dialog-footer">
            <el-button @click="viewDialogVisible = false">关闭</el-button>
            </span>
        </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getVisitorAppointmentList,
  getVisitorAppointmentById,
  createVisitorAppointment,
  updateVisitorAppointment,
  deleteVisitorAppointment,
} from '@/api/services.js'
import { getCompanyList } from '@/api/personnel.js'
import { searchVisitors } from '@/api/users.js'
import { Search, Plus, Delete } from '@element-plus/icons-vue'

const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = reactive({ name: '', phone: '', dateCondition: 'after', visitDate: '', status: '' })
const appointmentFormRef = ref(null)
const showSearchBar = ref(false)
const visitorOptions = ref([])
const searchLoading = ref(false)
let searchTimeout = null

const getInitialFormState = () => ({
  appointment_id: null,
  visitor_id: null,
  visited_company_id: null,
  visit_purpose: '',
  visitDate: '',
  visitTime: ''
});

const appointmentForm = reactive(getInitialFormState())

const appointmentFormRules = {
  visitor_id: [{ required: true, message: '请选择访客', trigger: 'change' }],
  visit_purpose: [{ required: true, message: '请输入访问目的', trigger: 'blur' }],
  visitDate: [{ required: true, message: '请选择访问日期', trigger: 'change' }],
  visitTime: [{ required: true, message: '请选择访问时间', trigger: 'change' }],
}

const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add')
const appointmentDetail = ref({})
const companyOptions = ref([])

const dialogTitle = computed(() => dialogType.value === 'add' ? '添加访客预约' : '编辑访客预约')

const getStatusText = (status) => ({ 0: '待审批', 1: '已批准', 2: '已拒绝', 3: '已入园', 4: '已离园', 5: '已取消' }[status] || '未知状态')
const getStatusType = (status) => ({ 0: 'info', 1: 'primary', 2: 'danger', 3: 'warning', 4: 'success', 5: 'info' }[status] || '')
const formatDateTime = (isoString) => isoString ? new Date(isoString).toLocaleString() : 'N/A';

const fetchCompanyList = async () => {
  try {
    const res = await getCompanyList({ page: 1, pageSize: 1000 })
    companyOptions.value = res.data.data.list
  } catch (error) {
    ElMessage.error('获取企业列表失败')
  }
}

const searchVisitorsMethod = (query) => {
  if (query) {
    if (searchTimeout) {
      clearTimeout(searchTimeout)
    }
    searchTimeout = setTimeout(() => {
      searchLoading.value = true
      searchVisitors(query)
        .then(response => {
          if (response.data && response.data.code === 200) {
            visitorOptions.value = response.data.data.map(item => ({
              value: item.id,
              label: `${item.name} (${item.phone})`,
              ...item
            }))
          } else {
            visitorOptions.value = []
          }
        })
        .catch(() => {
          visitorOptions.value = []
        })
        .finally(() => {
          searchLoading.value = false
        })
    }, 300)
  } else {
    visitorOptions.value = []
  }
}

const fetchAppointmentList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      visitor_name: searchForm.name,
      visitor_phone: searchForm.phone,
      status: searchForm.status,
    }
    if (searchForm.visitDate) {
      if (searchForm.dateCondition === 'before') params.end_date = searchForm.visitDate
      else params.start_date = searchForm.visitDate
    }
    const res = await getVisitorAppointmentList(params)
    tableData.value = res.data.data.list
    total.value = res.data.data.total
  } catch (error) {
    ElMessage.error('获取访客预约列表失败')
  } finally {
    loading.value = false
  }
}

const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
}

const handleSearch = () => {
  currentPage.value = 1
  fetchAppointmentList()
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.dateCondition = 'after'
  searchForm.visitDate = ''
  searchForm.status = ''
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAppointmentList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAppointmentList()
}

const resetAppointmentForm = () => {
    Object.assign(appointmentForm, getInitialFormState());
    if (appointmentFormRef.value) {
        appointmentFormRef.value.resetFields();
    }
}

const handleAdd = () => {
  resetAppointmentForm()
  dialogType.value = 'add'
  dialogVisible.value = true
}

const handleEdit = async (row) => {
  resetAppointmentForm()
  dialogType.value = 'edit'
  try {
    const res = await getVisitorAppointmentById(row.appointment_id)
    const data = res.data.data
    const [visitDate, visitTime] = data.expected_visit_time.split('T')
    
    appointmentForm.appointment_id = data.appointment_id
    appointmentForm.visitor_id = data.visitor.id
    appointmentForm.visited_company_id = data.visited_company?.company_id || null
    appointmentForm.visit_purpose = data.visit_purpose
    appointmentForm.visitDate = visitDate
    appointmentForm.visitTime = visitTime.substring(0,8)

    if (data.visitor) {
      visitorOptions.value = [{ 
        value: data.visitor.id, 
        label: `${data.visitor.name} (${data.visitor.phone})`
      }]
    }
    
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取预约详情失败')
  }
}

const handleView = async (row) => {
  try {
    const res = await getVisitorAppointmentById(row.appointment_id)
    appointmentDetail.value = res.data.data
    viewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取预约详情失败')
  }
}

const updateStatus = async (row, status, confirmText, successText) => {
  await ElMessageBox.confirm(confirmText, '提示', { type: 'warning' })
  try {
    await updateVisitorAppointment(row.appointment_id, { status })
    ElMessage.success(successText)
    fetchAppointmentList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleApprove = (row) => updateStatus(row, 1, '确认批准该访客的访问申请吗？', '已批准')
const handleReject = (row) => updateStatus(row, 2, '确认拒绝该访客的访问申请吗？', '已拒绝')
const handleCheckIn = (row) => updateStatus(row, 3, '确认该访客已入园？', '操作成功，访客已入园')
const handleCheckOut = (row) => updateStatus(row, 4, '确认该访客已离园？', '操作成功，访客已离园')

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该预约信息吗？', '警告', { type: 'warning' })
    .then(async () => {
      try {
        await deleteVisitorAppointment(row.appointment_id)
        ElMessage.success('删除成功')
        fetchAppointmentList()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }).catch(() => {})
}

const submitForm = () => {
  appointmentFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    const formData = {
      visitor_id: appointmentForm.visitor_id,
      visited_company_id: appointmentForm.visited_company_id,
      visit_purpose: appointmentForm.visit_purpose,
      expected_visit_time: `${appointmentForm.visitDate}T${appointmentForm.visitTime}`
    }

    try {
      if (dialogType.value === 'add') {
        await createVisitorAppointment(formData)
        ElMessage.success('添加成功')
      } else {
        await updateVisitorAppointment(appointmentForm.appointment_id, formData)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      fetchAppointmentList()
    } catch (error) {
        const msg = error.response?.data?.message || '操作失败'
        ElMessage.error(msg)
    }
  })
}

onMounted(() => {
  fetchAppointmentList()
  fetchCompanyList()
})
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

.date-filter-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* Custom style for buttons with icons */
:deep(.add-btn),
:deep(.batch-delete-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Success Button */
:deep(.el-button--success) {
  background-color: rgba(103, 194, 58, 0.1) !important;
  color: #67C23A !important;
  border-color: rgba(103, 194, 58, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--success:hover) {
  background-color: rgba(103, 194, 58, 0.15) !important;
  border-color: rgba(103, 194, 58, 0.3) !important;
}

/* Warning Button */
:deep(.el-button--warning) {
  background-color: rgba(230, 162, 60, 0.1) !important;
  color: #E6A23C !important;
  border-color: rgba(230, 162, 60, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--warning:hover) {
  background-color: rgba(230, 162, 60, 0.15) !important;
  border-color: rgba(230, 162, 60, 0.3) !important;
}

/* Info Button */
:deep(.el-button--info) {
  background-color: rgba(144, 147, 153, 0.1) !important;
  color: #909399 !important;
  border-color: rgba(144, 147, 153, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--info:hover) {
  background-color: rgba(144, 147, 153, 0.15) !important;
  border-color: rgba(144, 147, 153, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}

/* Danger Button */
:deep(.el-button--danger) {
  background-color: rgba(245, 108, 108, 0.1) !important;
  color: #F56C6C !important;
  border-color: rgba(245, 108, 108, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--danger:hover) {
  background-color: rgba(245, 108, 108, 0.15) !important;
  border-color: rgba(245, 108, 108, 0.3) !important;
}
</style> 